/**
 * @fileoverview
 *
 *  Example of configuration section related to datastore
 *  
 *  "datastore": {
 *     "type": "mysql",
 *     "host": "127.0.0.1",
 *     "port": 3306,
 *	   "user": "uxperf",
 *     "password": "uxperf",
 *     "db": "uxperf",
 *     "table": "datapkgs"
 *   }
 *
 * TODO: if there will be need to speedup, it could be reasonable to use connection pool
 */

var MySQLDataStore = module.exports = function(cfg) {
	MySQLDataStore.NDEBUG = cfg['ndebug'];
	var table = cfg['table'] || 'datapkgs';
	
	MySQLDataStore.db = db = require('mysql-native').createTCPClient(cfg['host'], cfg['port']);
	db.auto_prepare = true;
	db.auth(cfg['db'], cfg['user'], cfg['password']);
	
	db.query(
		'create table if not exists ' + table + '(' +
		'  id bigint unsigned not null auto_increment primary key,' +
		'  day date not null,' +
		'  servertime bigint not null,' +
		'  clienttime bigint not null,' +
		'  timeoffset int not null default 0,' +
		'  data TEXT not null' + //text=64 kB, mediumtext=16 MB, largetext=4 GB
		') character set utf8'
		//+ ' partition by key(day) (partition m2012 values less than 20130101, partition m2013 values less than maxvalue)'
	);
	MySQLDataStore.saveSQL = 'insert into ' + table + '(day, data, timeoffset, servertime, clienttime) values (curdate(), ?, ?, ?, ?)';
	db.prepare(MySQLDataStore.saveSQL);
	console.log('Prepared SQL: %s', MySQLDataStore.saveSQL);
	
	console.log('MySQL Data Store initialized');
};

MySQLDataStore.save = function(data, timeOffset, serverTime, clientTime) {
	MySQLDataStore.NDEBUG || console.log('save - timeOffset: %d, serverTime: %d, clientTime: %d, data: %s', timeOffset, serverTime, clientTime, data);
	MySQLDataStore.db.execute(MySQLDataStore.saveSQL, [data, timeOffset, serverTime, clientTime]);
};

MySQLDataStore.close = function() {
	MySQLDataStore.db.close();
};